package me.aip.mov.handler;

import lombok.extern.slf4j.Slf4j;
import me.aip.mov.annotation.GlobalResult;
import me.aip.mov.response.ResponseResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {
    /**
     * 标记名称
     */
    private final static String GLOBAL_RESPONSE_RESULT = "GLOBAL_RESPONSE_RESULT";

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        //判断请求是否有包装标记
        GlobalResult responseResultAip = (GlobalResult)request.getAttribute(GLOBAL_RESPONSE_RESULT);
        return responseResultAip==null?false:true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse serverHttpResponse) {
        if (body instanceof ResponseResult){
                return body;
        }
        if (body instanceof LinkedHashMap){
            Map map = (LinkedHashMap)body;
            if(map.get("error")!=null){
                return ResponseResult.builder()
                        .code(map.get("status")==null?null:map.get("status").toString())
                        .message(map.get("message")==null?null:map.get("message").toString())
                        .data(map.get("error")==null?null:map.get("error").toString())
                        .build();
            }
        }
        return ResponseResult.success(body);
    }
}
